//
//  InviteFamilyMemberViewController.m
//  家校互通
//
//  Created by 李赛 on 15/6/15.
//  Copyright (c) 2015年 姬鑫宇. All rights reserved.
//

#import "InviteFamilyMemberViewController.h"
#import "InvateImageCollectionViewCell.h"
#import "InvitaeDetailTableViewCell.h"
#import "BLParaEnumParamiter.h"
#import "InviteCodeTableViewCell.h"
@interface InviteFamilyMemberViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,ConnectControlDelegate>{
    ConnectControl *connectCtr;
    UIImage *inviteCode;
    UIImageView *codeImgView;
}

@property (nonatomic, retain) NSArray *familyMembersArray;

@end

@implementation InviteFamilyMemberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _contentTableView.delegate=self;
    _contentTableView.dataSource=self;
    self.title=@"邀请家庭成员";
    // Do any additional setup after loading the view.
    connectCtr = [ConnectControl showForView:self.view];
    connectCtr.delegate=self;
    
    if (connectCtr.superview!=nil && connectCtr.loading==NO)
    {
        [connectCtr setLoading:YES];
    }
    
    codeImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    codeImgView.center = CGPointMake(DSF_SCREENWIDTH/2, 300);
    codeImgView.backgroundColor = [UIColor clearColor];
    
    [_contentTableView addSubview:codeImgView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.numberOfLines = 2;
    label.text = @"打开家长汇客户端，扫一扫注册并登陆客户端";
    label.center = CGPointMake(DSF_SCREENWIDTH/2, 440);
    [_contentTableView addSubview:label];
}

- (CIImage *)createQRForString:(NSString *)qrString {
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
    // 创建filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 设置内容和纠错级别
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    // 返回CIImage
    return qrFilter.outputImage;
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

- (void)connect{
    [DSFUserInfo getMyFamilyMembers:^(BOOL result, NSString *failMessage,NSArray *familyMembers, NSError *error) {
        if (result) {
            [DSFUserInfo getMyInvitationCode:^(BOOL result, NSString *code, NSError *error) {
                [ConnectControl removeFromView:self.view];
                _familyMembersArray = [NSArray arrayWithArray:familyMembers];
                
                CIImage *image = [self createQRForString:code];
                inviteCode = [self createNonInterpolatedUIImageFormCIImage:image withSize:200];
                codeImgView.image = inviteCode;
                
                [_contentTableView reloadData];
            }];
            
        }else{
            HHAlertView *alertview = [[HHAlertView alloc] initWithTitle:@"失败" detailText:failMessage addView:self.view cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alertview.mode = HHAlertViewModeError;
            [alertview showWithBlock:^(NSInteger index) {
                NSLog(@"%ld",index);
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    } withToken:[DSFUserInfo shareUserInstance].token andClazzId:[DSFUserInfo shareUserInstance].clazz_user.clazz.id];
}
#pragma mark -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InvitaeDetailTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"InvitaeDetailTableViewCell" forIndexPath:indexPath];
    [vCell setCollectionViewDataSourceDelegate:self contentIndex:collectionViewTagForContentMImage];
    return vCell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark -UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  130;

}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    return nil;
}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
//{
//
//}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}



#pragma mark---UICollectionViewDataSource--
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_familyMembersArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FamilyMember *model = [_familyMembersArray objectAtIndex:indexPath.row];
    InvateImageCollectionViewCell *vCell=[collectionView dequeueReusableCellWithReuseIdentifier:@"InvateImageCollectionViewCell" forIndexPath:indexPath];
    [vCell setContentOfFamilyMember:model];
    return vCell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
       return nil;
}
#pragma mark---UICollectionViewDelegate--
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
